//
//  HomeView.swift
//  memo
//
//  Created by DaleGuo on 2023/10/1.
//

import SwiftUI
import WidgetKit

struct HomeView: View {
    @EnvironmentObject var homeVM: HomeViewModel

    @Environment(\.scenePhase) var scenePhase

    @State var show_setting_sheet = false

    @State var show_mode: ShowMode = .memos

    @State var add_fail = false

    var body: some View {
        NavigationStack {
            ScrollView {
                searchBar

                if !homeVM.memos.isEmpty {
                    if show_mode == .memos {
                        memoList
                    } else {
                        todoList
                    }
                } else {
                    emptyMemos
                }
            }
            .toolbar(content: {
                ToolbarItem(placement: .topBarLeading) {
                    Menu(content: {
                        Button("Mode", action: showModeToggle)

                        NavigationLink {
                            TrashView()
                        } label: {
                            Button {} label: {
                                Label("Recycling Station", systemImage: "trash")
                            }
                        }

                        NavigationLink {
                            CountDownView()
                        } label: {
                            Button {} label: {
                                Label("Countdown", systemImage: "clock")
                            }
                        }

                    }, label: {
                        Image(systemName: "ellipsis")
                    })
                }

                ToolbarItem(placement: .topBarTrailing) {
                    Image(systemName: "plus")
                        .onTapGesture {
                            // 判断最新的memo是否有内容

                            guard let memo_last = homeVM.memos.first else {
                                add_memo()
                                return
                            }

                            if memo_last.content.isEmpty, memo_last.title.isEmpty {
                                add_fail.toggle()

                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                                    add_fail.toggle()
                                }

                            } else {
                                add_memo()
                            }
                        }
                }

            })
            .navigationTitle("Memos")
        }
//        .onAppear { customFunction() }
//        .onChange(of: scenePhase, initial: true) { _, newPhase in
//
//            if newPhase == .active {
//                customFunction()
//            }
//        }
    }
}

extension HomeView {
    enum ShowMode {
        case memos
        case todos
    }

    private func customFunction() {
//        print("!!!!")
//        homeVM.applyChange()
//        homeVM.addSubscriber()
        homeVM.getAllMemos()
        
//        print("下面是vm中的数据")
//        homeVM.memos.forEach { MemoEntity in
//            MemoEntity.todos.forEach { TodoEntity in
//                print(TodoEntity.content + "  -  "+TodoEntity.is_completed.description)
//            }
//        }
    }

    private var searchBar: some View {
        TextField("search", text: $homeVM.searchText)
            .padding(10)
            .background(Color("Background"))
            .clipShape(RoundedRectangle(cornerRadius: 10))
            .padding()
    }

    private var memoList: some View {
        VStack {
            ForEach(homeVM.memos) { memo in

                // 只对最新的一个产生效果
                if memo.id == homeVM.memos.first!.id {
                    MemoView(memo: memo, add_fail: $add_fail)
                        .padding(.horizontal)
                } else {
                    MemoView(memo: memo, add_fail: .constant(false))
                        .padding(.horizontal)
                }
            }
        }
        .transition(.move(edge: .bottom))
        .animation(.bouncy, value: homeVM.memos)
    }

    private var todoList: some View {
        ForEach(homeVM.day_todos.keys.sorted(by: >), id: \.self) { day in
            VStack(alignment: .leading) {
                Text(day.formatted(date: .abbreviated, time: .omitted))
                    .font(.headline)

                Divider()
                    .padding(.vertical, 1)

                // sort todo
                ForEach(homeVM.day_todos[day]!.sorted(by: { $0.updated_date > $1.updated_date })) { todo in
                    TodoRow(todo: todo)
                }
            }
            .padding()
        }
    }

    private var emptyMemos: some View {
        VStack {
            Text("You haven't added any memos yet. Click the + to get start 🥳")
                .font(.system(size: 20))
                .multilineTextAlignment(.center)
                .fontWeight(.medium)
                .padding(40)
                .foregroundStyle(.secondaryText)

            Image(systemName: "note")
                .font(.system(size: 150))
                .foregroundStyle(.secondaryText.opacity(0.3))

            Spacer()
        }
    }

    private func showModeToggle() {
        if show_mode == .memos {
            show_mode = .todos
        } else {
            show_mode = .memos
        }
    }

    private func add_memo() {
        homeVM.addMemo()
    }
}

#Preview {
    HomeView()
        .environmentObject(HomeViewModel()) // 为了让预览有效果，这里在extion中定义了HomeViewModel
}
